package com.example.enjoyfood

import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.ui.PlayerView
import java.io.IOException

class RecipeDetailActivity : AppCompatActivity() {

    private lateinit var recipeImageView: ImageView
    private lateinit var recipeNameTextView: TextView
    private lateinit var recipeTextView: TextView
    private lateinit var videoTextView: TextView
    private lateinit var playerView: PlayerView
    private var player: ExoPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recipe_detail)

        recipeImageView = findViewById(R.id.recipe_detail_image)
        recipeNameTextView = findViewById(R.id.recipe_detail_name)
        recipeTextView = findViewById(R.id.recipe_detail_content)
        videoTextView = findViewById(R.id.recipe_detail_video)
        playerView = findViewById(R.id.video_player_view)

        val recipeName = intent.getStringExtra("recipe_name")
        val recipeImage = intent.getIntExtra("recipe_image", 0)
        val recipeFileName = intent.getStringExtra("recipe_file")
        val videoUrl = intent.getStringExtra("video_url")

        recipeNameTextView.text = recipeName
        recipeImageView.setImageResource(recipeImage)

        // 加载外部文本文件
        loadRecipeFromFile(recipeFileName)

        videoTextView.text = videoUrl

        // 添加返回按键
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 初始化视频播放器
        if (!videoUrl.isNullOrEmpty()) {
            initializePlayer(videoUrl)
        }

        // 隐藏 videoTextView
        videoTextView.visibility = View.GONE
    }

    private fun loadRecipeFromFile(fileName: String?) {
        if (fileName != null) {
            try {
                val inputStream = assets.open(fileName)
                val text = inputStream.bufferedReader().use { it.readText() }
                recipeTextView.text = text
            } catch (e: IOException) {
                e.printStackTrace()
                recipeTextView.text = "无法加载菜谱内容"
            }
        }
    }

    private fun initializePlayer(videoUrl: String) {
        player = ExoPlayer.Builder(this).build()
        playerView.player = player

        val mediaItem = MediaItem.fromUri(Uri.parse(videoUrl))
        player?.setMediaItem(mediaItem)
        player?.prepare()
        player?.playWhenReady = true
    }

    override fun onDestroy() {
        super.onDestroy()
        releasePlayer()
    }

    private fun releasePlayer() {
        player?.release()
        player = null
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }
}